from browser import document
from browser import html
from browser import alert
from browser import ajax
from browser import window
import json

saveUserInfo = document["saveUserInfo"]
userName = document["inputUsername"]
inputUserGroup = document["inputUserGroup"]
inputUserRemask = document["inputUserRemask"]
displayUserInfo = document["displayUserInfo"]
userAddWindw = document["userAddWindw"]

def returnIndex(req):
    window.location.href = "./index.html?page=users"

def addUserDatas(req):
    data = json.loads(req.text)
    # print(data)
    displayUserInfo.clear()
    userAddWindw.clear()

    if data["code"] == 5:
        displayUserInfo <= html.B("请扫描以下二维码进行获取动态密码(推荐使用[google authenticator]或者[Microsoft Authenticator])")


        qcodeDiv = html.DIV()
        qcodeDiv.id = "qrcode"
        displayUserInfo <= qcodeDiv

        makeCode = window.makeCode
        makeCode(data["msg"])

        displayUserInfo <= html.BR()
        btn = html.BUTTON("点我返回主页面")
        btn.className = "btn btn-primary"
        btn.bind("click",returnIndex)
        displayUserInfo <= btn

    else:
        alert(req.text)
        window.location.href = "./index.html?page=users"


def addUser(ev):
    usernameVal = userName.value
    userRemask = inputUserRemask.value
    userGroupVal = ""

    for item in inputUserGroup:
        if item.selected:
            if userGroupVal == "":
                userGroupVal = str(item.value)
                continue

            userGroupVal = userGroupVal + ":" + str(item.value)

    reqData = {}
    reqData["username"] = usernameVal
    reqData["group"] = userGroupVal
    reqData["remask"] = userRemask

    request = ajax.Ajax()
    request.bind("complete", addUserDatas)
    request.open("POST", "/manageUsers", False)
    request.send(reqData)

    userName.value = ""
    inputUserRemask.value = ""

def updateOptions(req):
    data = json.loads(req.text)
    if data["Code"] == 0:
        for item in  data["Data"]:
            option = html.OPTION(item["Names"])
            option.value = item["Id"]

            inputUserGroup <= option

request = ajax.Ajax()
request.bind("complete", updateOptions)
request.open("GET", "/showGroups", False)
request.send()

saveUserInfo.bind("click",addUser)